package com.glsc.ngateway.opmanage.controller.other;


import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.glsc.ngateway.common.api.ldap.dto.LdapEhrEmpDto;
import com.glsc.ngateway.common.api.common.enums.Constant;
import com.glsc.ngateway.common.api.common.enums.DictConstant;
import com.glsc.ngateway.common.base.domain.mysql.gateway.other.DigitalKeyFees;
import com.glsc.ngateway.common.base.domain.mysql.gateway.other.ProductRelation;
import com.glsc.ngateway.common.base.domain.mysql.gateway.platform.User;
import com.glsc.ngateway.common.api.platform.dto.other.DigitalKeyDto;
import com.glsc.ngateway.common.api.common.utils.PageUtil;
import com.glsc.ngateway.common.api.common.ex.Result;
import com.glsc.ngateway.opmanage.dto.DigitalKeyFeeDto;
import com.glsc.ngateway.opmanage.dto.DigitalKeyFeesDto;
import com.glsc.ngateway.opmanage.dto.DigitalKeyFeesImportDto;
import com.glsc.ngateway.opmanage.dto.DigitalKeyFeesItemImportDto;
import com.glsc.ngateway.opmanage.service.UserService;
import com.glsc.ngateway.opmanage.service.other.DigitalKeyService;
import com.glsc.ngateway.opmanage.service.other.ProductRelationService;
import com.glsc.ngateway.opmanage.utils.RequestTool;
import com.glsc.ngateway.opmanage.utils.report.ReportUploadContext;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author: libj
 * @Date: 2022/6/27
 * @Desc: 数字证书信息管理
 */
@RestController
@RequestMapping("/api/digitalkey")
@Api(value = "DigitalKeyController", tags = {"数字证书信息信息管理"})
public class DigitalKeyController {

    private static Logger logger = LoggerFactory.getLogger(DigitalKeyController.class);

    @Resource
    private DigitalKeyService digitalKeyService;

    @Resource
    private ProductRelationService productRelationService;

    @Resource
    private UserService userService;

    @Resource
    private RequestTool requestTool;

    @GetMapping("/listpage")
    @ApiOperation(value = "数字证书信息分页查询", notes = "数字证书信息分页查询")
    public Result<Page<DigitalKeyDto>> listPage(
            @ApiParam(value = "使用部门") @RequestParam(required = false) String useDepartment,
            @ApiParam(value = "对应平台") @RequestParam(required = false) String keyPlatform,
            @ApiParam(value = "发证机构") @RequestParam(required = false) String keyIssueBranch,
            @ApiParam(value = "证书序列号") @RequestParam(required = false) String keyNo,
            @ApiParam(value = "保管人") @RequestParam(required = false) String custodianList,
            @ApiParam(value = "保管人所在部门") @RequestParam(required = false) String custodianDeptName,
            @ApiParam(value = "证书有效期") @RequestParam(required = false) String keyExpireDate,
            @ApiParam(value = "状态") @RequestParam(required = false) String keyStatus,
            @ApiParam(value = "页码从1开始") @RequestParam(required = false) Integer pageNo,
            @ApiParam(value = "每页显示条数 默认10") @RequestParam(required = false) Integer pageSize,
            HttpServletRequest request) {
        User currentUser = requestTool.getUserFromRequest(request);
        Map<String, Object> param = new HashMap<>();
        if (StrUtil.isNotEmpty(useDepartment)) {
            param.put("LIKE_useDepartment", useDepartment);
        }
        if (StrUtil.isNotEmpty(keyPlatform)) {
            param.put("LIKE_keyPlatform", keyPlatform);
        }
        if (StrUtil.isNotEmpty(keyIssueBranch)) {
            param.put("LIKE_keyIssueBranch", keyIssueBranch);
        }
        if (StrUtil.isNotEmpty(keyNo)) {
            param.put("LIKE_keyNo", keyNo);
        }
        if (StrUtil.isNotEmpty(keyStatus)) {
            param.put("LIKE_keyStatus", keyStatus);
        }
        if (StrUtil.isNotEmpty(custodianDeptName)) {
            param.put("LIKE_custodianDeptName", custodianDeptName);
        }
        if (StrUtil.isNotEmpty(custodianList)) {
            Map<String, Object> productRelationParam = new HashMap<>();
            productRelationParam.put("EQ_deleted", DictConstant.NO);
            productRelationParam.put("EQ_relationType", DictConstant.PROD_RELATION_TYPE_DIGITAL_KET_CUSTODIAN);
            productRelationParam.put("INSTR_relatedId", custodianList);
            List<ProductRelation> productRelationServiceList = productRelationService.findList(productRelationParam);
            if (CollectionUtil.isEmpty(productRelationServiceList)) {
                param.put("IN_keyId", "0");
            } else {
                List<Integer> keyIdList = productRelationServiceList.stream().map(ProductRelation::getKeyId).collect(Collectors.toList());
                param.put("IN_keyId", StringUtils.join(keyIdList, ","));
            }
        }
        if (StrUtil.isNotEmpty(keyExpireDate)) {
            if ("长期".equals(keyExpireDate)) {
                param.put("EQ_keyExpireDate", keyExpireDate);
            } else {
                param.put("LTE_keyExpireDate", keyExpireDate);
            }
        }
        param.put("EQ_keyDeleted", DictConstant.NO);

        if (CollectionUtil.isNotEmpty(currentUser.getRoles())
                && currentUser.getRoles().stream().anyMatch(role -> role.getName().equals(Constant.DIGITAL_KEY_ADMIN))
                && currentUser.getRoles().stream().anyMatch(role -> role.getName().equals(Constant.ROLE_DIGITAL_KEY_ROLE))) {
            //组长可以查看自己和其组员作为保管员的数字证书
            //查询当前登录用户下属用户
            List<LdapEhrEmpDto> userList = userService.findUserListByUserLeaderAccount(currentUser.getUsername());
            List<String> queryList = new ArrayList<>();
            if (CollectionUtil.isNotEmpty(userList)) {
                queryList = userList.stream().map(LdapEhrEmpDto::getBadge).collect(Collectors.toList());
            }
            queryList.add(currentUser.getUsername());
            if (StrUtil.isNotEmpty(custodianList)) {
                if (queryList.contains(custodianList)) {
                    queryList = new ArrayList<>();
                    queryList.add(custodianList);
                } else {
                    queryList = new ArrayList<>();
                }
            }

            if (CollectionUtil.isEmpty(queryList)) {
                param.put("IN_keyId", "0");
            } else {
                Map<String, Object> productRelationParam = new HashMap<>();
                productRelationParam.put("EQ_deleted", DictConstant.NO);
                productRelationParam.put("EQ_relationType", DictConstant.PROD_RELATION_TYPE_DIGITAL_KET_CUSTODIAN);
                productRelationParam.put("INSTR_relatedId", StringUtils.join(queryList, ","));
                List<ProductRelation> productRelationServiceList = productRelationService.findList(productRelationParam);
                if (CollectionUtil.isEmpty(productRelationServiceList)) {
                    param.put("IN_keyId", "0");
                } else {
                    List<Integer> keyIdList = productRelationServiceList.stream().map(ProductRelation::getKeyId).collect(Collectors.toList());
                    param.put("IN_keyId", StringUtils.join(keyIdList, ","));
                }
            }
        }

        Page<DigitalKeyDto> page = digitalKeyService.findPage(requestTool.getUserFromRequest(request), param, PageUtil.initPageNo(pageNo), PageUtil.initPageSize(pageSize));
        return Result.successData(page);
    }

    @PostMapping("/create")
    @ApiOperation(value = "创建数字证书信息", notes = "创建数字证书信息")
    public Result save(@ApiParam(required = true, value = "数字证书信息") @RequestBody DigitalKeyDto digitalKeyDto, HttpServletRequest request) {
        logger.info("创建数字证书信息，数字证书信息：" + digitalKeyDto);
        try {
            digitalKeyService.save(digitalKeyDto, null, requestTool.getUserFromRequest(request));
            return Result.successData("创建成功");
        } catch (Exception e) {
            logger.error("创建数字证书信息失败" + e.getLocalizedMessage(), e);
            return Result.failData(e.getMessage());
        }
    }

    @PostMapping("/update")
    @ApiOperation(value = "更新数字证书信息", notes = "更新数字证书信息")
    public Result update(@ApiParam(required = true, value = "数字证书信息") @RequestBody DigitalKeyDto digitalKeyDto, HttpServletRequest request) {
        logger.info("更新数字证书信息，数字证书信息：" + digitalKeyDto);
        try {
            digitalKeyService.update(digitalKeyDto, null, requestTool.getUserFromRequest(request));
            return Result.successData("更新成功");
        } catch (Exception e) {
            logger.error("更新数字证书信息失败" + e.getLocalizedMessage(), e);
            return Result.failData(e.getMessage());
        }
    }

    @PostMapping("/delete")
    @ApiOperation(value = "删除数字证书信息", notes = "删除数字证书信息")
    public Result delete(@ApiParam(required = true, value = "数字证书信息") @RequestBody DigitalKeyDto digitalKeyDto, HttpServletRequest request) {
        logger.info("删除数字证书信息，数字证书信息：" + digitalKeyDto);
        try {
            digitalKeyService.updateDeletedByKeyId(digitalKeyDto.getKeyId(), requestTool.getUserFromRequest(request));
            return Result.successData("删除成功");
        } catch (Exception e) {
            logger.error("删除数字证书信息失败" + e.getLocalizedMessage(), e);
            return Result.failData(e.getMessage());
        }
    }

    @PostMapping("/digitalKeyFees/import/result")
    @ApiOperation(value = "数字证书分摊结果导入", notes = "数字证书分摊结果导入")
    public Result<?> uploadDigitalKeyFees(@RequestPart("file") MultipartFile file,
                                          @ApiParam(value = "交易所") @RequestParam(required = true) String tradingPost,
                                          @ApiParam(value = "计费年度") @RequestParam(required = true) String annualFeeDate) throws IOException {
        ReportUploadContext<DigitalKeyFeesImportDto, String> context = digitalKeyService.digitalKeyFeesImport(file, tradingPost, annualFeeDate);
        return context.isCheckPass() ? Result.successData(context.getReadRes()) : Result.failData(String.join(",", context.getCheckRes()));
    }

    @PostMapping("/digitalKeyFees/import/detail")
    @ApiOperation(value = "数字证书分摊明细导入", notes = "数字证书分摊明细导入")
    public Result<?> uploadDigitalKeyFeesItem(@RequestPart("file") MultipartFile file,
                                              @ApiParam(value = "交易所") @RequestParam(required = true) String tradingPost,
                                              @ApiParam(value = "计费年度") @RequestParam(required = true) String annualFeeDate) throws IOException {
        ReportUploadContext<DigitalKeyFeesItemImportDto, String> context = digitalKeyService.digitalKeyFeesItemImport(file, tradingPost, annualFeeDate);
        return context.isCheckPass() ? Result.successData(context.getReadRes()) : Result.failData(String.join(",", context.getCheckRes()));
    }

    @GetMapping("/digitalKeyFees/listpage")
    @ApiOperation(value = "数字证书分摊结果分页查询", notes = "数字证书分摊结果分页查询")
    public Result<Page<DigitalKeyFees>> listDigitalKeyDtoPage(
            @ApiParam(value = "内部编码") @RequestParam(required = false) String brnOrgNo,
            @ApiParam(value = "财务代码") @RequestParam(required = false) String finCode,
            @ApiParam(value = "营业部名称") @RequestParam(required = false) String brnOrgNm,
            @ApiParam(value = "计费年度") @RequestParam(required = false) String annualFeeDate,
            @ApiParam(value = "页码从1开始") @RequestParam(required = false) Integer pageNo,
            @ApiParam(value = "每页显示条数 默认10") @RequestParam(required = false) Integer pageSize,
            HttpServletRequest request) {

        Page<DigitalKeyFees> digitalKeyFeesPage = digitalKeyService.findDigitalKeyFeesPage(brnOrgNo, finCode, brnOrgNm, annualFeeDate, pageNo, pageSize);
        return Result.successData(digitalKeyFeesPage);
    }

    @GetMapping("/digitalKeyFees/findOne")
    @ApiOperation(value = "数字证书分摊结果详情页", notes = "数字证书分摊结果详情页")
    public Result<DigitalKeyFeeDto> findDigitalKeyDtoById(
            @ApiParam(value = "id") @RequestParam(required = true) String id,
            HttpServletRequest request) {
        DigitalKeyFeeDto digitalKeyFees = digitalKeyService.findDigitalKeyFeeDtoById(id);
        return Result.successData(digitalKeyFees);
    }


    @GetMapping("/digitalKeyFees/sendDigitalKeyEmail")
    @ApiOperation(value = "发送数字证书年费分摊结果邮件", notes = "发送数字证书年费分摊结果邮件")
    public Result<DigitalKeyFeeDto> sendDigitalKeyEmail(
            @ApiParam(value = "id") @RequestParam(required = true) String id,
            HttpServletRequest request) {
        DigitalKeyFeeDto digitalKeyFees = digitalKeyService.findDigitalKeyFeeDtoById(id);
        String res = digitalKeyService.sendDigitalKeyFeesEmail(digitalKeyFees);
        DigitalKeyFeesDto digitalKey = digitalKeyFees.getDigitalKeyFees();
        if (Objects.nonNull(digitalKey)) {
            digitalKey.setStatus("2");
            digitalKey.setEmailSendRes("邮件发送失败");
        }
        if (StringUtils.isNotBlank(res) && !res.contains("失败")) {
            if (Objects.nonNull(digitalKey)) {
                digitalKey.setStatus("1");
                digitalKey.setEmailId(res);
                digitalKey.setEmailSendRes("邮件发送成功");
            }
        }
        DigitalKeyFees keyFees = new DigitalKeyFees();
        BeanUtils.copyProperties(digitalKey, keyFees);
        return Result.successData(digitalKeyService.saveDigitalKeyFees(keyFees));
    }


    @GetMapping("/digitalKeyFees/sendAllEmail")
    @ApiOperation(value = "触发异步批量发送数字证书年费分摊邮件", notes = "触发异步批量发送数字证书年费分摊邮件")
    public Result<DigitalKeyFeeDto> sendDigitalKeyEmails(HttpServletRequest request) {
        digitalKeyService.dealDigitalKeyFeesEmailTask();
        return Result.successData("处理成功");
    }


//    @GetMapping("/logpage")
//    @ApiOperation(value = "查询数字证书信息操作日志分页")
//    public Result<QueryResults<DigitalKeyLog>> logpage(
//            @ApiParam(value = "使用部门") @RequestParam(required = false) String useDepartmentId,
//            @ApiParam(value = "数字证书类别") @RequestParam(required = false) String keyClass,
//            @ApiParam(value = "对应平台") @RequestParam(required = false) String keyPlatform,
//            @ApiParam(value = "发证机构") @RequestParam(required = false) String keyIssueBranch,
//            @ApiParam(value = "证书序列号") @RequestParam(required = false) String keyNo,
//            @ApiParam(value = "页码从1开始") @RequestParam(required = false) Integer pageNo,
//            @ApiParam(value = "每页显示条数 默认10") @RequestParam(required = false) Integer pageSize) {
//        Map<String, Object> param=new HashMap<>();
//        if (StrUtil.isNotEmpty(useDepartmentId)) {
//            param.put("EQ_useDepartmentId", useDepartmentId);
//        }
//        if (StrUtil.isNotEmpty(keyClass)) {
//            param.put("EQ_keyClass", keyClass);
//        }
//        if (StrUtil.isNotEmpty(keyPlatform)) {
//            param.put("EQ_keyPlatform", keyPlatform);
//        }
//        if (StrUtil.isNotEmpty(keyIssueBranch)) {
//            param.put("EQ_keyIssueBranch", keyIssueBranch);
//        }
//        if (StrUtil.isNotEmpty(keyNo)) {
//            param.put("LIKE_keyNo", keyNo);
//        }
//        param.put("EQ_keyDeleted", DictConstant.NO);
//        return Result.successData(
//                digitalKeyService.logPage(
//                        param,
//                        PageUtil.initPageNo(pageNo),
//                        PageUtil.initPageSize(pageSize)
//                ));
//    }

}
